//
//  RootLoginViewController.m
//  BVCMS Search
//
//  Created by Allen Thomas on 9/13/10.
//

#import "RootLoginViewController.h"
#import "HttpConnectionHandler.h"
#import "BVCMSAppDelegate.h"
#import "GenericXMLParser.h"

@implementation RootLoginViewController

@synthesize loginButton;
@synthesize table;
@synthesize organizations;

/* 
 Setup the login view by loading the background image, also sets the table background to clear.
 */
- (void)viewDidLoad {
	NSLog(@"ViewDidLoad");
	[self loadUserDefaults];
	
	UIImage *background = [UIImage imageNamed: @"login.png"];    
	UIImageView *imageView = [[UIImageView alloc] initWithImage: background]; 
	
	[self.view addSubview: imageView];
	[self.view sendSubviewToBack: imageView];
	[imageView release];
	
	table.backgroundColor = [UIColor clearColor];
			
	[super viewDidLoad];
	NSLog(@"End ViewDidLoad");
}


#pragma mark Login

/*	
 Login Action method:
 This action performs authentication and if authenticated, display the Search Form View
 */
- (IBAction)login:(id)sender 
{
	NSLog(@"Login Action");
	
	NSString *urlString = [NSString stringWithFormat:@"https://%@/iphone/Organizations", [self getText:serverField] ];
	
	urlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
	
	NSLog(@"%@", urlString);
	NSURL *url = [NSURL URLWithString:urlString];
	
	HttpConnectionHandler *connectionHandler = [HttpConnectionHandler withURL:url andUsername:[self getText:usernameField] andPassword:[self getText:passwordField]];
	
	connectionHandler.errorCallback = @selector(login_error_callback:);
	connectionHandler.callback = @selector(login_callback:);
	connectionHandler.delegate = self;
	[connectionHandler processRequest];

	[loginButton setEnabled:NO];
	[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
	
	[self textFieldDone:textFieldBeingEdited];
}


/*
 Gets a textfield value, if nil then return a blank string
 */
-(NSString*)getText:(UITextField*)textField {
	if( textField.text == nil ) {
		return @"";
	} else {
		return textField.text;
	}
}

/*
 Login action successful callback.  
 Stops the activity indicator and creates a SearchFormView.  It also sets the server, username, and password
 for the delegate.
 */
-(void) login_callback:(NSData *)data {
	NSString *output = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
	
	NSLog(@"%@", output);
	
	// Stop activity indicator
	[loginButton setEnabled:YES];
	[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
	
	if([output isEqualToString:@"not authorized"]) {
		UIAlertView *connectionError = [[UIAlertView alloc] initWithTitle:@"Login Failure" message:@"Invalid Username or Password" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
		[connectionError show];
		[connectionError release];
	} else {
		// Save username and server settings
		[self saveUserDefaults];
		
		// Set global connection settings
		BVCMSAppDelegate *delegate = [[UIApplication sharedApplication] delegate];
		delegate.cmsServer = [self getText:serverField];
		delegate.username = [self getText:usernameField];
		delegate.password = [self getText:passwordField];
		
		[self parseXml:data];
		
		delegate.organizations = organizations;
		[delegate login];
	}
	NSLog(@"Output released"); 
	[output release];
}

/* 
 Login unsuccessful callback function.
 Sets the enables the login button and disables the activity indicator.
 */
-(void) login_error_callback:(NSError *)error {
	NSLog(@"Connection failed! Error - %@",
          [error localizedDescription]);
	
	[loginButton setEnabled:YES];
	[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
	
	UIAlertView *connectionError = [[UIAlertView alloc] initWithTitle:@"Connection Error" message:[error localizedDescription] delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
	[connectionError show];
	[connectionError release];
}


/*
 Callback functions that handles the 'organizations' tag
 */
-(void) handleElement_Organizations: (NSDictionary*) attributes {
	NSLog(@"Organizations handler");
	if(organizations) {
		[organizations release];
	}
	self.organizations = [[NSMutableArray alloc] init];
}

/*
 Callback function that handles the 'organization' tag.
 */
-(void) handleElement_Organization: (NSDictionary*) attributes {
	NSLog(@"Organization handler");
	[self.organizations addObject:attributes];
}

/*
 Creates an xml parser and begins parsing the xml data.
 */
-(void) parseXml:(NSData *)data {
	NSXMLParser *xmlParser = [[NSXMLParser alloc] initWithData:data];
	
	//Initialize the delegate.
	GenericXMLParser *parser = [[GenericXMLParser alloc] init];
	parser.delegate = self;
	
	//Set delegate
	[xmlParser setDelegate:parser];
	
	//Start parsing the XML file.
	BOOL success = [xmlParser parse];
	
	if(success)
		NSLog(@"No Errors");
	else
		NSLog(@"Error Error Error!!!");
	
	[parser release];
	[xmlParser release];
}



#pragma mark UserDefaults

/*
 Load user defaults from standard user defaults.
 */
-(void)loadUserDefaults {	
	NSLog(@"loadUserDefualts");

	prefs = [NSUserDefaults standardUserDefaults];

	NSLog(@"End ViewDidLoad");

}

/* 
 Save user defaults to standard user defaults.
 */
-(void)saveUserDefaults {
	[prefs setValue:usernameField.text forKey:@"username"];
	[prefs setValue:serverField.text forKey:@"cmsserver"];
	[prefs synchronize];
}



#pragma mark UIKeyboard handling

//method to move the view up/down whenever the keyboard is shown/dismissed
-(void)setViewMovedUp:(BOOL)movedUp
{
	[UIView beginAnimations:nil context:NULL];
	[UIView setAnimationDuration:0.3]; // if you want to slide up the view
	
	CGRect rect = self.view.frame;
	if (movedUp)
	{
		// 1. move the view's origin up so that the text field that will be hidden come above the keyboard 
		// 2. increase the size of the view so that the area behind the keyboard is covered up.
		rect.origin.y = kMin - textFieldBeingEdited.frame.origin.y ;
	}
	else
	{
		// revert back to the normal state.
		rect.origin.y = 0;
	}
	self.view.frame = rect;
	[UIView commitAnimations];
}


/*
 Triggered when the keyboard is shown.
 */
- (void)keyboardWillShow:(NSNotification *)notif
{
	//keyboard will be shown now. depending for which textfield is active, move up or move down the view appropriately
	if ([textFieldBeingEdited isFirstResponder])		
	{
		[self setViewMovedUp:YES];
	}
	else if (![textFieldBeingEdited isFirstResponder])
	{
		[self setViewMovedUp:NO];		
	}
}

/* 
 Triggered when the keyboard is hidden.
 */
- (void)keyboardWillHide:(NSNotification *)notif
{
	[self setViewMovedUp:NO];
}

/*
 Triggered when the view is displayed.  This is not called when the view is instantiated.
 */
- (void)viewWillAppear:(BOOL)animated
{
	self.title = @"Login";
	
	// register for keyboard notifications
	[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) 	 
												 name:UIKeyboardWillShowNotification object:self.view.window]; 
	[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) 
												 name:UIKeyboardWillHideNotification object:self.view.window]; 
}

/* 
 Triggered when the view is not active.
 */
- (void)viewWillDisappear:(BOOL)animated
{
	// unregister for keyboard notifications while not visible.
	[[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil]; 
}




#pragma mark Text Field Delegate Methods 

/*
 Triggered when the text field is beginning to be edited.
 */
- (void)textFieldDidBeginEditing:(UITextField *)textField {
	textFieldBeingEdited = textField;	
	[self setViewMovedUp:YES]; 
}


#pragma mark View Background Tap Action
/*
 This action is performed when the user clicks anywhere on the view 
 */
- (IBAction)backgroundTap:(id)sender
{
	[textFieldBeingEdited resignFirstResponder];
}


#pragma mark Table Methods

/*
 This action is performed when a row is selected.
 */
-(NSIndexPath *)tableView:(UITableView *)tableView
  willSelectRowAtIndexPath:(NSIndexPath *)indexPath { 
	return nil;
}

/*
 This action is performed when a textfield has finished being edited.
 */
-(IBAction)textFieldDone:(id)sender {
	[sender resignFirstResponder];
}

/*
 Returns number of sections in the table.
 */
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

/*
 Returns the number of rows in the table.
 */
- (NSInteger)tableView:(UITableView *)table
 numberOfRowsInSection:(NSInteger)section {
	return kNumberOfEditableRows;
}

/*
 Returns a UITableViewCell for a row and section.
 */
- (UITableViewCell *)tableView:(UITableView *)tableView
		 cellForRowAtIndexPath:(NSIndexPath *)indexPath {
	static NSString *SimpleTableIdentifier = @"SimpleTableIdentifier";
	
	UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:SimpleTableIdentifier];
	if (cell == nil) {
		cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault 
									   reuseIdentifier:SimpleTableIdentifier] autorelease];
		cell.accessoryType = UITableViewCellAccessoryNone;
		cell.selectionStyle = UITableViewCellSelectionStyleNone;
		
		UITextField *textField = [[UITextField alloc] initWithFrame: CGRectMake(110, 12, 180, 25)];

		textField.adjustsFontSizeToFitWidth = YES;
		textField.textColor = [UIColor colorWithRed:56.0f/255.0f green:84.0f/255.0f blue:135.0f/255.0f alpha:1];
		textField.font = [UIFont systemFontOfSize:14.0];
		
		textField.keyboardType = UIKeyboardTypeDefault;
		textField.returnKeyType = UIReturnKeyDone;
		textField.clearsOnBeginEditing = NO;
		
		[textField setDelegate:self];
		[textField addTarget:self
							action:@selector(textFieldDone:) forControlEvents:UIControlEventEditingDidEndOnExit];
		
		textField.backgroundColor = [UIColor whiteColor];
		textField.autocorrectionType = UITextAutocorrectionTypeNo; // no auto correction support
		textField.autocapitalizationType = UITextAutocapitalizationTypeNone; // no auto capitalization support
		textField.textAlignment = UITextAlignmentLeft;
		textField.tag = [indexPath row];
		
		textField.clearButtonMode = UITextFieldViewModeNever; // no clear 'x' button to the right
		[textField setEnabled: YES];
		
		[cell addSubview:textField];
		
		
		switch([indexPath row]) {
			case kUsernameRowIndex:
				cell.textLabel.text = @"Username";
				textField.text = [prefs stringForKey:@"username"];
				textField.placeholder = @"Enter Username";
				usernameField = textField;
				break;
			case kPasswordRowIndex:
				cell.textLabel.text = @"Password";
				textField.placeholder = @"Enter Password";
				textField.secureTextEntry = YES;
				passwordField = textField;
				break;
			case kServerRowIndex:
				cell.textLabel.text = @"Server";
				textField.placeholder= @"Enter BVCMS Server";
				textField.text = [prefs stringForKey:@"cmsserver"];
				serverField = textField;
				break;
		}
		
		[textField release];

		cell.textLabel.font = [UIFont boldSystemFontOfSize:14.0];
	}
	

	return cell;    	
	
}


#pragma mark Memory Management

/*
 Free up memory.
 */
- (void)dealloc {
	[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;

	[loginButton release];
	[table release];
	[organizations release];
    [super dealloc];
}


@end
